package com.ytjj.qmyx.admin.annotation;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.utils.IPUtil;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.admin.constants.SysLogConstants;
import com.ytjj.qmyx.admin.model.Admin;
import com.ytjj.qmyx.admin.model.AdminErrorLog;
import com.ytjj.qmyx.admin.model.AdminLog;
import com.ytjj.qmyx.admin.service.ExceptionLogService;
import com.ytjj.qmyx.admin.service.MemberService;
import com.ytjj.qmyx.admin.service.OperationLogService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 切面处理类，操作日志异常日志记录处理
 *
 * @Version 1.0
 * 
 */

@Aspect
@Component
public class OperLogAspect {

    @Resource
    private MemberService memberService;
    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    private ExceptionLogService exceptionLogService;

    @Value("${log.version}")
    private String operVer;


    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.ytjj.qmyx.admin.annotation.OperLog)")
    public void operLogPoinCut() {
    }

    /**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     */
    @Pointcut("execution(* com.ytjj.qmyx.admin.controller..*.*(..))")
    public void operExceptionLogPoinCut() {
    }


    /**
     * 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
     *
     * @param joinPoint 切入点
     * @param keys      返回结果
     */
    @AfterReturning(value = "operLogPoinCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        AdminLog adminLog = new AdminLog();
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取操作
            OperLog opLog = method.getAnnotation(OperLog.class);
            if (opLog != null) {
                String operModul = opLog.operModule();
                String operType = opLog.operType();
                String operDesc = opLog.operDesc();
                // 操作模块
                adminLog.setOperModule(operModul);
                // 操作类型
                adminLog.setOperType(operType);
                // 操作描述
                adminLog.setOperDesc(operDesc);
            }
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            // 请求方法
            adminLog.setOperMethod(methodName);

            // 请求的参数
            Object[] args = joinPoint.getArgs();
            Object[] arguments = new Object[args.length];
            //将参数所在的数组转换成json
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof ServletRequest
                        || args[i] instanceof ServletResponse
                        || args[i] instanceof MultipartFile) {
                    continue;
                }
                arguments[i] = args[i];
            }
            String paramter = "";
            if (arguments != null) {
                try {
                    paramter = JSONObject.toJSONString(arguments);
                } catch (Exception e) {
                    paramter = arguments.toString();
                }
            }
            // 请求参数
            if (!SysLogConstants.LOGIN_OPERATION.equals(adminLog.getOperType())){
                adminLog.setOperRequestParam(paramter);
            }else{
                //脱敏
                adminLog.setOperRequestParam(paramter.substring(paramter.indexOf(",\"tel\"")));
            }

            // 返回结果
            adminLog.setOperResponseParam(JSON.toJSONString(keys));

            Admin admin = memberService.getAdmin();
            // 请求用户ID
            adminLog.setUserId(admin.getId());
            // 请求用户名称
            adminLog.setUserName(admin.getName());
            // 请求IP
            String ip = IPUtil.getIpAddress(TokenUtil.getRequest());
            if (StringUtils.isNotBlank(ip)){
                String address =IPUtil.getAddressByIp(ip);
                adminLog.setOperIp(String.format("%s(%s)",ip,address));
            }
            // 请求URI
            adminLog.setOperUri(request.getRequestURI());
            // 创建时间
            adminLog.setCreateTime(new Date());
            // 操作版本
            adminLog.setOperVersion(operVer);
            operationLogService.insert(adminLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 异常返回通知，用于拦截异常日志信息 连接点抛出异常后执行
     *
     * @param joinPoint 切入点
     * @param e         异常信息
     */
    @AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        AdminErrorLog adminErrorLog = new AdminErrorLog();
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            // 请求方法名
            adminErrorLog.setOperMethod(methodName);

            // 请求的参数
            Object[] args = joinPoint.getArgs();
            Object[] arguments = new Object[args.length];
            //将参数所在的数组转换成json
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof ServletRequest
                        || args[i] instanceof ServletResponse
                        || args[i] instanceof MultipartFile) {
                    continue;
                }
                arguments[i] = args[i];
            }
            String paramter = "";
            if (arguments != null) {
                try {
                    paramter = JSONObject.toJSONString(arguments);
                } catch (Exception exception) {
                    paramter = arguments.toString();
                }
            }
            // 请求参数
            adminErrorLog.setExcRequestParam(paramter);

            // 异常名称
            adminErrorLog.setExcName(e.getClass().getName());
            // 异常信息
            adminErrorLog.setExcMessage(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace()));
            Admin admin = memberService.getAdmin();
            // 操作员ID
            adminErrorLog.setUserId(admin.getId());
            // 操作员名称
            adminErrorLog.setUserName(admin.getName());
            // 操作URI
            adminErrorLog.setOperUri(request.getRequestURI());
            // 操作员IP
            String ip = IPUtil.getIpAddress(TokenUtil.getRequest());
            if (StringUtils.isNotBlank(ip)){
                String address =IPUtil.getAddressByIp(ip);
                adminErrorLog.setUserIp(String.format("%s(%s)",ip,address));
            }

            // 操作版本号
             adminErrorLog.setOperVersion(operVer);
            // 发生异常时间
            adminErrorLog.setCreateTime(new Date());
            exceptionLogService.insert(adminErrorLog);
        } catch (Exception e2) {
            e2.printStackTrace();
        }

    }


    /**
     * 转换request 请求参数
     *
     * @param paramMap request获取的参数数组
     */
    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }

    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }

    public static void main(String[] args) {
        String s = "[{\"pwd\":\"123456\",\"tel\":\"admin@admin.com\",\"verCode\":\"2\",\"verKey\":\"captcha:admin:37cbbb86-239c-47a9-8a2d-8703f7a64561\"}]";
        System.out.println(s.substring(s.indexOf(",\"tel\"")));
    }

}
